package es.udc.pfc.davidparedes.web.pages.user;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import es.udc.pfc.davidparedes.model.director.Director;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;

import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.ADMIN)
public class UpdateDirector {
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private UserService userService;
    
    @Property
    private Long updateDirectorId;
    
    @Property
    private Long removeDirectorId;

    @Property
    private String firstName;

    @Property
    private String lastName;

    @Property
    private String email;
    
    @Property
    private String nif;
    
    @Component
    private Form updateDirectorForm;
    
    @Component
    private Form removeDirectorForm;
    
    void onActivate(Long id) {
    	try {
       		
    		Director director = userService.findDirector(id);
    		updateDirectorId = removeDirectorId = id;
    		
    		firstName = director.getFirstName();
    		lastName = director.getLastName();
    		email = director.getEmail();
    		nif = director.getNif();
    		
			} catch (InstanceNotFoundException e) {
		}
    }

    Object onValidateFromUpdateDirectorForm() throws InstanceNotFoundException {
    	
        if (!updateDirectorForm.isValid()) {
            return this;
        }
    
		userService.findDirector(updateDirectorId);
        userService.updateDirector(updateDirectorId, firstName, lastName, email, nif);
        
        return AdminStores.class;
        
    }
    
    Object onValidateFromRemoveDirectorForm() throws InstanceNotFoundException {
    	userService.deactivateDirector(removeDirectorId);
    	return AdminStores.class;
    }

}
